<template>
  <container title="发布商品">

    <div class="main-card" v-loading="loading">
      <goods-form-cat ref="catRef" v-show="formStep < 2"/>

      <el-tabs v-model="tabPaneIndex" v-show="formStep > 1">
        <el-tab-pane v-for="(item, index) in tabPaneList"
                     :label="item.label" :name="item.name" :key="index">
          <div style="height: 20px"></div>
          <component :is="item.component" :ref="item.name"/>
        </el-tab-pane>
      </el-tabs>

      <div style="margin-top: 20px">
        <el-affix position="bottom" :offset="20" ref="affix">
          <el-button :disabled="formStep < 2" icon="el-icon-arrow-left" @click="toPrev">上一步</el-button>
          <el-button :disabled="formStep > 2" type="primary" @click="toNext">
            下一步
            <i class="el-icon-arrow-right el-icon--right"></i>
          </el-button>
          <el-button type="success" @click="formSubmit" icon="el-icon-edit">保存</el-button>
          <el-button type="info" v-if="$route.query.id" @click="formSubmitCopy" icon="el-icon-document-copy">另存为
          </el-button>
          <el-button @click="toGoodsList" icon="el-icon-refresh-left">返回列表</el-button>
        </el-affix>
      </div>
    </div>
  </container>
</template>
<script lang="ts">
import {
  defineComponent, reactive, Ref, ref, getCurrentInstance,
  onMounted, defineAsyncComponent, toRefs
} from 'vue'
import http from '@/plugin/http'
import {ElMessage} from 'element-plus'
import {ComponentInternalInstance} from "@vue/runtime-core";
import {useRoute, useRouter} from "vue-router";
import {useStore} from "vuex";

export default defineComponent({

  name: 'goods-form',

  components: {
    GoodsFormCat: defineAsyncComponent(() =>
        import('./components/GoodsFormCat.vue')),
    GoodsFormBaseGeneral: defineAsyncComponent(() =>
        import('./components/GoodsFormBaseGeneral.vue')),
    GoodsFormBaseVirtual: defineAsyncComponent(() =>
        import('./components/GoodsFormBaseVirtual.vue')),
    GoodsFormBaseResource: defineAsyncComponent(() =>
        import('./components/GoodsFormBaseResource.vue')),
    GoodsFormAttr: defineAsyncComponent(() =>
        import('./components/GoodsFormAttr.vue')),
    GoodsFormSpec: defineAsyncComponent(() =>
        import('./components/GoodsFormSpec.vue')),
    GoodsFormDetail: defineAsyncComponent(() =>
        import('./components/GoodsFormDetail.vue')),
    GoodsFormShipping: defineAsyncComponent(() =>
        import('./components/GoodsFormShipping.vue')),
    GoodsFormIntegral: defineAsyncComponent(() =>
        import('./components/GoodsFormIntegral.vue'))
  },

  setup() {
    const loading = ref<boolean>(false)
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    const instance = getCurrentInstance() as ComponentInternalInstance
    const state = reactive({
      tabPaneIndex: 'base',
      tabPaneList: []
    })
    const affix: Ref = ref(null)
    const formStep = ref(1)
    const catRef: Ref = ref(null)
    let form: Record<string, string> = {
      cat_id: '', model_id: '152559205140856834',
      goods_id: ''
    }

    const toPrev = () => {
      if (state.tabPaneIndex === 'base') return formStep.value = 1
      changeTabPane('prev')
    }

    const toNext = () => {

      if (formStep.value === 1) {
        const categories = catRef.value.getData()
        if (!categories.length) return ElMessage.error("请选择分类")
        const lastCategory = categories[categories.length - 1]
        form.cat_id = lastCategory.cat_id
        form.model_id = lastCategory.model_id
        execComponentMethod('base', 'init', {cat_path: categories})
        getModelAttribute()
        getGatherInfo()
        // if (!this.form.cat_id) return
        // let catPath = this.$refs.cat.getPathList()
        // this.form.model_id = catPath[catPath.length - 1].model_id
        // this.getModelAttribute();
        // this.()
        // this.$refs.base[0].init({cat_path: catPath})
      }
      if (formStep.value > 1) return changeTabPane('next')
      formStep.value++
      setTimeout(() => affix.value.update(), 30)
    }

    const getGoodsInfo = async () => {
      const goodsId = route.query.id
      if (!goodsId) return
      const res = await http.get('/goods/detail', {
        goods_id: goodsId
      })
      if (res.data.code !== 0) return ElMessage.error(res.data.message)
      const data: { goods_type: number } = res.data.data
      if (data.goods_type === 1) buildTabBar('general')
      if (data.goods_type === 2) buildTabBar('virtual')
      if (data.goods_type === 3) buildTabBar('resource')
      formStep.value = 2
      init(data)
    }

    const getGatherInfo = async () => {
      const gatherId = route.query.gather_id
      if (!gatherId) return
      const res = await http.get('/goods.gather/detail', {
        gather_id: gatherId,
        model_id: form.model_id || '221045624952487938'
      })
      if (res.data.code !== 0) return ElMessage.error(res.data.message)
      const data: { goods_type: number } = res.data.data
      if (data.goods_type === 1) buildTabBar('general')
      if (data.goods_type === 2) buildTabBar('virtual')
      if (data.goods_type === 3) buildTabBar('resource')
      formStep.value = 2
      console.log(data)
      init(data)
    }

    // 初始化
    const init = (data) => {
      initComponent('base', data)
      initComponent('attr', data.goods_attr)
      initComponent('detail', data)
      initComponent('integral', data)
      initComponent('shipping', data)
      initComponent('spec', data)
      for (let i in form) {
        if (typeof data[i] !== 'undefined') form[i] = data[i]
      }
      getModelAttribute()
    }


    // 改变选项卡
    const changeTabPane = (direction: string) => {
      let index = state.tabPaneList.findIndex((item: Record<string, string>) =>
          item.name === state.tabPaneIndex)
      let target = index
      if (direction === 'prev' && index > 0) target = index - 1
      if (direction === 'next' && index < state.tabPaneList.length - 1) target = index + 1
      state.tabPaneIndex = (state.tabPaneList[target] as { name: '' }).name
    }

    const initComponent = (name: string, data: any, maxWait?: number) => {
      // console.log(name)
      // console.log(instance.refs[name])
      if (instance.refs[name]) return (instance.refs[name] as any).init(data)
      if (maxWait && maxWait > 300) return
      setTimeout(() => {
        if (typeof maxWait === 'undefined') maxWait = 30
        initComponent(name, data, maxWait + 30)
      }, 30)
    }

    // 获取分类属性
    const getModelAttribute = async (): Promise<void> => {
      if (!form.model_id) return
      const res = await http.get('/goods.model/attribute', {
        model_id: form.model_id
      })
      if (res.data.code !== 0) return
      let data = res.data.data
      for (let i in data.spec) data.spec[i].checked = []
      execComponentMethod('attr', 'setDynamicForm', data.base)
      execComponentMethod('spec', 'setAttributeList', data.spec)
    }

    // 执行组件方法
    const execComponentMethod = (name: string, method: string, data?: any): any => {
      let component: any = null
      let isGetSome = method.indexOf('get') > -1
      if (instance.refs[name]) component = instance.refs[name]
      if (null === component) return isGetSome ? data : null
      return component[method](data)
    }

    // 获取组件数据
    const getComponentFormData = (name: string, defaultData: any) => {
      return execComponentMethod(name, 'getFormData', defaultData)
    }

    const buildTabBar = (type: string): void => {
      let tabPaneList: Record<string, string>[] = []
      if (type === 'general') {
        tabPaneList = [
          {label: '基础信息', name: 'base', component: 'goods-form-base-general'},
          {label: '基础属性', name: 'attr', component: 'goods-form-attr'},
          {label: '图文详情', name: 'detail', component: 'goods-form-detail'},
          {label: '价格库存', name: 'spec', component: 'goods-form-spec'},
          {label: '物流信息', name: 'shipping', component: 'goods-form-shipping'},
          {label: '积分规则', name: 'integral', component: 'goods-form-integral'},
        ]
      } else if (type === 'resource') {
        tabPaneList = [
          {label: '基础信息', name: 'base', component: 'goods-form-base-resource'},
          {label: '商品详情', name: 'detail', component: 'goods-form-detail'},
          {label: '积分规则', name: 'integral', component: 'goods-form-integral'},
        ]
      } else if (type === 'virtual') {
        tabPaneList = [
          {label: '基础信息', name: 'base', component: 'goods-form-base-virtual'},
          {label: '商品详情', name: 'detail', component: 'goods-form-detail'},
          {label: '所在地址', name: 'shipping', component: 'goods-form-shipping'},
          {label: '积分规则', name: 'integral', component: 'goods-form-integral'},
        ]
      }
      (state.tabPaneList as Record<string, string>[]) = tabPaneList
    }

    // 提交表单
    const formSubmit = async () => {
      form = {
        ...getComponentFormData('base', {}),
        ...form,
        ...getComponentFormData('detail', {}),
        ...getComponentFormData('integral', {}),
        ...getComponentFormData('shipping', {}),
        ...getComponentFormData('spec', {}),
      }
      form.goods_attr = getComponentFormData('attr', '')
      const api = '/goods/' + (form.goods_id ? 'edit' : 'add')
      const res = await http.post(api, form)
      if (res.data.code !== 0) return ElMessage.error(res.data.message)
      ElMessage.success(res.data.message)
      await store.dispatch('tbc_admin/close', {tagName: route.fullPath})
      await router.push(({name: 'goods-list', params: {t: new Date().getTime()}}))
    }

    const formSubmitCopy = () => {
      form.goods_id = ''
      formSubmit()
    }

    const toGoodsList = () => {
      router.push(({name: 'goods-list'}))
    }

    // 获取
    onMounted(() => {
      console.log('========')
      getGoodsInfo()
      if (!route.query.id) buildTabBar((route.query.type as string))
    })

    return {
      ...toRefs(state),
      toGoodsList,
      loading,
      affix,
      formStep,
      catRef,
      toNext,
      toPrev,
      formSubmit,
      formSubmitCopy
    }
  }
})
</script>
